{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# This notebook has been tested with \n",
    "* Python 3.5\n",
    "* OpenCV 3.1.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import cv2\n",
    "import matplotlib.pyplot as plt\n",
    "from PIL import Image\n",
    "import numpy as np\n",
    "import concurrent.futures\n",
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Save photo that has faces"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Direction is the target directory to save images\n",
    "def detectFace(filename, direction):\n",
    "    faceCascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n",
    "    image = cv2.imread(filename)\n",
    "    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "\n",
    "    faces = faceCascade.detectMultiScale(gray, 1.05, 3, minSize = (100,100))\n",
    "\n",
    "    if len(faces):\n",
    "        filename = filename.split('/')[1]\n",
    "        cv2.imwrite(direction + filename, image)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Open the source directory of images\n",
    "photoDir = 'female/'\n",
    "photoList = os.listdir(photoDir)\n",
    "# The target directory to save images\n",
    "direction = 'female_detect/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Multi-threading to speed up\n",
    "with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:\n",
    "    for photo in photoList:\n",
    "        try:\n",
    "            filename = photoDir+photo\n",
    "            executor.submit(detectFace, filename, direction)\n",
    "        except Exception as exc:\n",
    "            print(exc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Extract faces and save"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Open the source directory of images\n",
    "photoDir = 'woman_without_hair/'\n",
    "photoList = os.listdir(photoDir)\n",
    "# The target directory to save faces\n",
    "direction = 'woman_without_hair/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Direction is the target directory to save images\n",
    "def extractFace(filename, direction):\n",
    "    faceCascade = cv2.CascadeClassifier(\"haarcascade_frontalface_alt.xml\")\n",
    "    image = cv2.imread(filename)\n",
    "    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n",
    "\n",
    "    faces = faceCascade.detectMultiScale(gray, 1.05, 3, minSize = (100,100))\n",
    "    \n",
    "    filealt = filename.split('/')[1]\n",
    "\n",
    "    im = Image.open(filename)\n",
    "    i = 0\n",
    "    for (x, y, w, h) in faces:\n",
    "        filename = str(i) + filealt\n",
    "        center_x = x+w/2\n",
    "        center_y = y+h/2\n",
    "        b_dim = min(max(w,h)*1.2,im.width, im.height) \n",
    "        box = (center_x-b_dim/2, center_y-b_dim/2, center_x+b_dim/2, center_y+b_dim/2)\n",
    "        # Crop Image\n",
    "        crpim = im.crop(box).resize((224,224))\n",
    "        # Save Image\n",
    "        crpim.save(direction + filename)\n",
    "        i += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Multi-threading to speed up\n",
    "with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:\n",
    "    for photo in photoList:\n",
    "        try:\n",
    "            filename = photoDir+photo\n",
    "            executor.submit(extractFace, filename, direction)\n",
    "        except Exception as exc:\n",
    "            print(exc)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
